import os
import threading
from tkinter import Button

import json
from tkinter.ttk import Entry, Label

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrapCmd, wrap_with_try_except
from util.window.config_window.config_button import create_config_button
from util.comm.path import getConfigPath, getPath
from util.comm.msg_util import msg
import tkinter as tk


class WinExecParamTool():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getConfigPath()
        self.button = create_config_button(self, True)

        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        if isinstance(data, list):
            for index, c in enumerate(data):
                # 增加二级目录
                if 'is_active' in c:
                    if c['is_active'] == 0:
                        continue
                self.menu = self.create_tab(self.tab, c['menu'])
                self.elements.append(self.menu)
                content = c['content']
                params = content["params"]
                # 增加输入框
                map = {}
                if isinstance(params, list):
                    row = 1
                    for index, param in enumerate(params):
                        title = param['field_title']
                        field = param['field']

                        # 标题
                        self.label = Label(self.menu, text=title)
                        self.label.grid(row=row, column=0, padx=5, pady=5)

                        self.Entry = Entry(self.menu, width=36)
                        self.Entry.grid(row=row, column=1, padx=5, pady=5)

                        map[field] = self.Entry

                        row += 1

                        new_row = tk.Frame(self.menu)
                        new_row.grid(row=row, column=0, sticky='news')

                # 增加按钮
                cmd = content["cmd"]
                exe_file = content["exe_file"]
                button = content["button"]
                shell = content["shell"]
                self.button = Button(self.menu, text=button, command=lambda n=c['menu'],c=cmd,e=exe_file,m=map,s=shell: self.print_entry_sync(n,c,e,m,s), width=12)
                self.button.grid(row=row, column=1, padx=36, pady=5)

        else:
            print(data)

    def print_entry_sync(self, n, c, e, m, s):
        flag = "sync_flag_%s" % n
        if hasattr(self, flag) and getattr(self, flag) == '1':
            msg('正在处理,请勿重复操作')
            return
        setattr(self, flag, '1')
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=(c,e,m,s,)), lambda n=n: self.reset_sync(n)).execute_async()

    def reset_sync(self, n):
        flag = "sync_flag_%s" % n
        setattr(self, flag, '0')

    def print_entry(self, cmd, exe_file, m, s):
        project_path = getPath()
        exe = os.path.join(project_path, exe_file)
        cmd = cmd.replace('{exe}', exe)
        cmd = cmd.replace("\\", "\\\\\\")
        for key, value in m.items():
            v = ""
            try:
                v = value.get()
            except:
                pass
            cmd = cmd.replace(f"{{{key}}}", v)
        is_shell = True
        if s == '0':
            wrapCmd(f"{cmd}", is_shell)
        elif s == '1':
            is_shell = False
            wrapCmd(f"{cmd}", is_shell)
        elif s == '2':
            os.system(cmd)
        else:
            msg("shell参数错误")

    def create_tab(self, master_tabs, title):
        # 创建第一级tab t1
        tree_tab = tk.Frame(master_tabs)
        tree_tab.pack()

        master_tabs.add(tree_tab, text=title)
        return tree_tab
